﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Runtime;

namespace Gollie.Payment.Targetpay
{
	public class IDealBanks : IDeal
	{
		BankCollection banks = null;
		private string banksCacheKey = "bankscachekey";
		public IDealBanks()
			: this(false)
		{
		}

		public IDealBanks(bool testMode)
			: base(testMode)
		{
			banks = MemCache[banksCacheKey] as BankCollection;
			if (banks == null)
			{
				this.ProcessRequest(this.banksUrl, null);
				MemCache.Set(banksCacheKey, banks, new DateTimeOffset(DateTime.Now.AddDays(1)));
			}
		}

		protected override void ProcessTargetPayResponse(string response)
		{
			banks = new BankCollection();

			XmlDocument doc = new XmlDocument();
			doc.LoadXml(response);

			XmlNodeList bankList = doc.SelectNodes("/issuers/issuer");
			if (bankList.Count == 0)
				this.ThrowXmlException(doc);

			foreach (XmlNode bankNode in bankList)
			{
				string id = null;
				string name = null;

				try
				{
					id = bankNode.Attributes["id"].Value;
					name = bankNode.InnerText;
				}
				catch
				{
				}

				if (string.IsNullOrEmpty(id) == false &&
					string.IsNullOrEmpty(name) == false)
				{
					Bank bank = new Bank(id, name);

					banks.Add(bank);
				}
			}
		}

		public BankCollection Banks
		{
			get	{ return this.banks; }
		}
	}
}